import { updateEvaluationUsingPost } from '@/services/backend/evaluationController';
import { ProColumns, ProSchemaValueEnumMap, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { useModel } from '@umijs/max';
import { message, Modal } from 'antd';
import React from 'react';

interface Props {
  oldData?: API.Evaluation;
  modalVisible: boolean;
  studentEnumMap: ProSchemaValueEnumMap;
  coachEnumMap: ProSchemaValueEnumMap;
  planEnumMap: ProSchemaValueEnumMap;
  onSubmit: () => void;
  onCancel: () => void;
}

const UpdateModal: React.FC<Props> = (props) => {
  const { modalVisible, studentEnumMap, planEnumMap, onSubmit, onCancel, oldData } = props;

  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser ?? {};

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.EvaluationUpdateRequest) => {
    const hide = message.loading('正在更新');
    try {
      await updateEvaluationUsingPost({
        ...fields,
        coachId: currentUser.id,
      });
      hide();
      message.success('更新成功');
      return true;
    } catch (error: any) {
      hide();
      message.error(`更新失败${error.message}`);
      return false;
    }
  };

  const columns: ProColumns<API.EvaluationVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '被评估人',
      dataIndex: 'userId',
      valueEnum: studentEnumMap,
      hideInSearch: true,
    },
    {
      title: '训练名称',
      dataIndex: 'planId',
      valueEnum: planEnumMap,
      hideInSearch: true,
    },
    {
      title: '评分(0-10)',
      dataIndex: 'score',
      valueType: 'digit',
      fieldProps: {
        min: 0,
        max: 10,
      },
    },
    {
      title: '内容',
      dataIndex: 'content',
      valueType: 'textarea',
    },
  ];

  return (
    <Modal title={'更新'} open={modalVisible} destroyOnClose footer={null} onCancel={onCancel}>
      <ProTable
        type={'form'}
        columns={columns}
        form={{ initialValues: oldData }}
        onSubmit={async (value) => {
          const success = await handleUpdate({
            ...value,
            id: oldData?.id,
          });
          if (success) {
            onSubmit?.();
          }
        }}
      />
    </Modal>
  );
};
export default UpdateModal;
